#pragma once
#include <iostream>
#include <queue>
#include <string.h>
#include <pthread.h>

const int defaultcap = 5;

template <typename T>
class BlockQueue
{
private:
    bool IsFull() { return _q.size() >= _cap; }
    bool IsEmpty() { return _q.empty(); }

public:
    BlockQueue(int cap = defaultcap)
        : _cap(cap), _csleep_num(0), _psleep_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_full_cond, nullptr);
        pthread_cond_init(&_empty_cond, nullptr);
    }

    void Equeue(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        //生产者调用
        while(IsFull())
        {
            //应该让生产者进行等待
            //pthread_cond_wait调用成功，挂起当前线程之前，要先自动释放锁
            //当进程被唤醒的时候，默认是在临界区被唤醒，要从pthread_cond_wait成功返回，需要当前线程重新申请锁
            //如果我被唤醒了，但是申请锁失败了，就会在锁上等待
            _psleep_num++;
            std::cout<<"生产者进入休眠，_psleep_num:"<< _psleep_num<<std::endl;
            //问题1：Pthread_cond_wait可能调用失败，立刻返回来
            //问题2：pthread_cond_wait可能，条件并不满足，被伪唤醒了
            //所有是while
            pthread_cond_wait(&_full_cond,&_mutex);
            _psleep_num++;
        }

        //队列绝对有空间
        _q.push(in);
        if(_csleep_num>0)
        {
            pthread_cond_signal(&_empty_cond);
            std::cout<<"消费者被唤醒..."<<std::endl;
        }

        pthread_mutex_unlock(&_mutex);
    }

    T Pop()
    {
        //消费者调用
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            _csleep_num++;
            pthread_cond_wait(&_empty_cond,&_mutex);
            _csleep_num--;
        }

        T data = _q.front();
        _q.pop();
        std::cout<<"消费了一个任务"<<std::endl;

        if(_psleep_num>0)
        {
            pthread_cond_signal(&_full_cond);
            std::cout<<"生产者被唤醒..."<<std::endl;
        }

        pthread_mutex_unlock(&_mutex);

        return data;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_cond);
        pthread_cond_destroy(&_empty_cond);
    }

private:
    std::queue<T> _q; // 临界资源
    int _cap;         // 容量大小

    pthread_mutex_t _mutex;
    pthread_cond_t _full_cond;
    pthread_cond_t _empty_cond;

    int _csleep_num; // 消费者休眠的个数
    int _psleep_num; // 生产者休眠的个数
};